<template>
  <BasicModal v-bind="config" :title="currTitle" v-model:visible="visible" wrapClassName="loginSelectModal">
    <a-form ref="formRef" v-bind="layout" :model="formState" :rules="rules" :colon="false" class="loginSelectForm">
      <a-form-item v-if="isMultiBusiness" :validate-status="validate_status1">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>您隶属于多商户，请选择当前所在商户</span>
            </template>
            <a-avatar style="background-color: rgb(104, 208, 203)" :size="30"> 商户 </a-avatar>
          </a-tooltip>
        </template>
        <!--商户下拉内容-->
        <a-select v-model:value="formState.businessSelected"
                  @change="handleBusinessChange"
                  placeholder="请选择登录商户"
                  :class="{ 'valid-error': validate_status1 == 'error' }">
          <template #suffixIcon>
            <Icon icon="ant-design:gold-outline" />
          </template>
          <template v-for="business in businessList" :key="business.businessId">
            <a-select-option :value="business.businessId">{{ business.businessName }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item v-if="isMultiCompany" :validate-status="validate_status">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>您隶属于多公司，请选择当前所属公司</span>
            </template>
            <a-avatar style="background-color: #87d068" :size="30"> 公司 </a-avatar>
          </a-tooltip>
        </template>
        <!--公司下拉内容-->
        <a-select v-model:value="formState.companySelected"
                  @change="handleCompanyChange"
                  placeholder="请选择登录公司"
                  :class="{ 'valid-error': validate_status == 'error' }">
          <template #suffixIcon>
            <Icon icon="ant-design:gold-outline" />
          </template>
          <template v-for="company in companyList" :key="company.companyId">
            <a-select-option :value="company.companyId">{{ company.companyName }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button @click="handleSubmit" type="primary">确认</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, watch, unref, defineExpose, reactive, UnwrapRef } from 'vue';
  import { Avatar } from 'ant-design-vue';
  import { BasicModal } from '/@/components/Modal';
  import {
    getCurrentUserBusiness,
    selectBusiness,
    getCurrentUserCompany,
    selectCompany,
    selectBusinessAndCompany
  } from '/@/views/system/user/user.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { useRouter } from 'vue-router'
  import { PageEnum } from "/@/enums/pageEnum";

  const router = useRouter();
  const userStore = useUserStore();
  const { createMessage, notification } = useMessage();
  const props = defineProps({
    title: { type: String, default: '公司选择' },
    closable: { type: Boolean, default: false },
    username: { type: String, default: '' },
  });

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  interface FormState {
    businessSelected: string | undefined;
    companySelected: string | undefined;
  }

  const config = {
    maskClosable: false,
    closable: false,
    canFullscreen: false,
    width: '500px',
    minHeight: 20,
    maxHeight: 20,
  };
  const currTitle = ref('');
  //公司配置
  const isMultiCompany = ref(false);
  const currentCompanyName = ref('');
  // const companySelected = ref();
  const companyList = ref([]);
  const validate_status = ref('');
  //商户配置
  const isMultiBusiness = ref(false);
  const currentBusinessName = ref('');
  // const businessSelected = ref('');
  const businessList = ref([]);
  const validate_status1 = ref('');
  //弹窗显隐
  const visible = ref(false);
  //表单
  const formRef = ref();
  const rules = ref<any>({});
  //选择的公司商户信息
  const formState: UnwrapRef<FormState> = reactive({
    businessSelected: undefined,
    companySelected: undefined,
  });


  /**
   * 弹窗打开前处理
   */
  async function show() {
    //加载商户
    await loadBusinessList();
    //加载公司
    await loadCompanyList();
    //标题配置
    if (unref(isMultiCompany) && unref(isMultiBusiness)) {
      currTitle.value = '切换商户和公司';
    } else if (unref(isMultiCompany)) {
      currTitle.value =
        unref(currentCompanyName) && unref(currentCompanyName).length > 0 ? `公司切换（当前公司：${unref(currentCompanyName)}）` : props.title;
    } else if (unref(isMultiBusiness)) {
      currTitle.value =
        unref(currentBusinessName) && unref(currentBusinessName).length > 0 ? `商户切换（当前商户：${unref(currentBusinessName)}）` : props.title;
    }
    //效验rules
    rules.businessSelected = [{ required: unref(isMultiBusiness), message: "请选择商户", trigger: "change" }];
    rules.companySelected = [{required: unref(isMultiCompany), message: "请选择公司", trigger: "change" }];
    //model显隐
    if (unref(isMultiCompany) || unref(isMultiBusiness)) {
      visible.value = true;
    }
  }

  /**
   *加载商户信息
   */
  async function loadBusinessList() {
    isMultiBusiness.value = true;//商户和公司选择都显示
    const result = await getCurrentUserBusiness();
    if (!result.list || result.list.length == 0) {
      return;
    }
    let currentBusiness = result.list.filter((item) => item.businessId == result.businessId);
    businessList.value = result.list;
    formState.businessSelected = currentBusiness && currentBusiness.length > 0 ? result.businessId : '';
    currentBusinessName.value = currentBusiness && currentBusiness.length > 0 ? currentBusiness[0].businessName : '';
    // isMultiBusiness.value = true;
  }

  /**
   *加载公司信息
   */
  async function loadCompanyList() {
    isMultiCompany.value = true;//商户和公司选择都显示
    const result = await getCurrentUserCompany();
    if (!result.list || result.list.length == 0) {
      return;
    }
    let currentCompany = result.list.filter((item) => item.companyId == result.companyId);
    companyList.value = result.list;
    formState.companySelected = currentCompany && currentCompany.length > 0 ? result.companyId : '';
    currentCompanyName.value = currentCompany && currentCompany.length > 0 ? currentCompany[0].companyName : '';
    // isMultiCompany.value = true;
  }

  /**
   * 提交数据
   */
  async function handleSubmit() {
    if (unref(isMultiBusiness) && !unref(formState.businessSelected)) {
      validate_status1.value = 'error';
      return false;
    }
    if (unref(isMultiCompany) && !unref(formState.companySelected)) {
      validate_status.value = 'error';
      return false;
    }

    formRef.value
      .validate()
      .then(() => {
        //切换商户和公司选择
        businesAndCompanyResolve()
          .then(() => {
            createMessage.success('切换成功');
            //切换成功跳转首页
            router.push({ path: PageEnum.BASE_HOME});
            let { fullPath } = router.currentRoute.value;
            if(fullPath === PageEnum.BASE_HOME){
              window.location.reload(); //监测到路由发生跳转时刷新一次页面
            }
          })
          .catch((e) => {
            notification.warn({
              message: "提示",
              description: `商户和公司选择出现问题`,
              duration: 3
            });
          })
          .finally(() => {
            close();
          });
      })
      .catch((err) => {
        console.log("表单校验未通过error", err);
      });
  }

  /**
   *切换选择商户
   */
  function businessResolve() {
    return new Promise<void>(async (resolve, reject) => {
      if (!unref(isMultiBusiness)) {
        resolve();
      } else {
        const result = await selectBusiness({
          username: userStore.getUserInfo.username,
          curBusiness: unref(formState.businessSelected),
        });
        if (result.userInfo) {
          const userInfo = result.userInfo;
          userStore.setUserInfo(userInfo);
          resolve();
        } else {
          requestFailed(result);
          await userStore.logout();
          reject();
        }
      }
    });
  }

  /**
   *切换选择公司
   */
  function companyResolve() {
    return new Promise<void>(async (resolve, reject) => {
      if (!unref(isMultiCompany)) {
        resolve();
      } else {
        const result = await selectCompany({
          username: userStore.getUserInfo.username,
          curCompany: unref(formState.companySelected),
        });
        if (result.userInfo) {
          const userInfo = result.userInfo;
          userStore.setUserInfo(userInfo);
          resolve();
        } else {
          requestFailed(result);
          await userStore.logout();
          reject();
        }
      }
    });
  }

  /**
   *切换选择商户和公司
   */
  function businesAndCompanyResolve() {
    return new Promise<void>(async (resolve, reject) => {
      if (!unref(isMultiCompany)) {
        resolve();
      } else {
        const result = await selectBusinessAndCompany({
          username: userStore.getUserInfo.username,
          curBusiness: unref(formState.businessSelected),
          curCompany: unref(formState.companySelected),
        });
        if (result.userInfo) {
          const userInfo = result.userInfo;
          userStore.setUserInfo(userInfo);
          resolve();
        } else {
          requestFailed(result);
          await userStore.logout();
          reject();
        }
      }
    });
  }

  /**
   * 请求失败处理
   */
  function requestFailed(err) {
    notification.error({
      message: '登录失败',
      description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
      duration: 4,
    });
  }
  /**
   * 关闭model
   */
  function close() {
    businessClear();
  }

  function handleCompanyChange(e) {
    validate_status.value = "";
  }

  async function handleBusinessChange(e) {
    validate_status1.value = "";
    //根据选择的商户查询公司
    const result = await getCurrentUserCompany({ businessIds: e });
    if (!result.list || result.list.length == 0) {
      companyList.value = [];
      formState.companySelected = '';
      currentCompanyName.value = '请选择公司';
    } else {
      companyList.value = result.list;
    }
  }

  /**
   *初始化数据
   */
  function businessClear() {
    currTitle.value = '';
    isMultiCompany.value = false;
    currentCompanyName.value = '';
    formState.companySelected = '';
    companyList.value = [];
    validate_status.value = '';
    isMultiBusiness.value = false;
    currentBusinessName.value = '';
    formState.businessSelected = '';
    businessList.value = [];
    validate_status1.value = '';
    visible.value = false;
  }

  /**
   * 监听username
   */
  watch(
    () => props.username,
    (value) => {
      value && loadBusinessList();
    }
  );

  defineExpose({
    show,
  });
</script>
<style lang="less" scoped>
  .loginSelectForm {
    margin-bottom: -20px;
  }

  .loginSelectModal {
    top: 20px;
  }

  .valid-error .ant-select-selection__placeholder {
    color: #f5222d;
  }
</style>
